$(function(){
  init();
  $("input[name=newcategory]").hide();
  $("select[name=category]").change(function(){
    if($("select[name=category]").val()=='create'){
        $("select[name=category]").hide();
        $("input[name=newcategory]").show();
    }
  });
  $(".msg").each(function(){
    $(this).html(chrome.i18n.getMessage(jQuery(this).attr("tag")));
  });

});

function user_load(i){
  var a = new Date();
  var t = Math.ceil(a.getTime()/1000);
  var d =  JSON.parse(localStorage.siteuser);
  var vo = d[i];
  
  $.each(vo.cook,function(k,v){
    if(v.expirationDate < t){
      v.expirationDate = t + 9900;
    }
    if(v.hostOnly){
      delete v.domain;
    }
    delete v.hostOnly;
    delete v.session;
    v.url = vo.url;
    chrome.cookies.set(v);
  });
  chrome.tabs.create({url:vo.url,selected:true}, function(){});
}

function submit() {
  chrome.tabs.getSelected(null, function(tab){
    chrome.cookies.getAll({url:tab.url},function(c){
      var vo  = {};
      var d = [];
      var c_id = typeof(localStorage.categoryid)=='undefined'?1:localStorage.categoryid;
      if(typeof(localStorage.siteuser)!='undefined'){
        d = JSON.parse(localStorage.siteuser);
      }
      var l = (d.length+1);
      if($("input[name=site_user]").val()==''){
        vo.label = (tab.title == '')?'Site-User '+l:tab.title;
      }else{
        vo.label = $("input[name=site_user]").val();
      }

      if($("select[name=category]").val()=='create'){
        c_id ++;
        var category = typeof(localStorage.category)=='undefined'?{}:JSON.parse(localStorage.category);
        category['c'+c_id] = $("input[name=newcategory]").val();
        localStorage.category = JSON.stringify(category);
        localStorage.categoryid = c_id;
        vo.category = 'c'+c_id;
        $("select[name=category]").show();
        $("input[name=newcategory]").hide();
      }else{
        vo.category = $("select[name=category]").val();
      }
      vo.url  = tab.url;
      vo.cook = c;
      d.push(vo);
      localStorage.siteuser = JSON.stringify(d);
      $.each(c,function(k,v){
        chrome.cookies.remove({url:tab.url,name:v.name,storeId:v.storeId});
      });
      chrome.tabs.executeScript(tab.id,{"code":"window.location.href = window.location.href;"});
      $("select[name=category]").find("option:not(.msg)").remove();
      init();
      $("input[name=site_user]").val('');
    });
  });
}

function init() {
  $('#user-list').empty();
  var d = typeof(localStorage.siteuser)=='undefined'?[]:JSON.parse(localStorage.siteuser);
  var c = typeof(localStorage.category)=='undefined'?{}:JSON.parse(localStorage.category);
  
  $.each(c,function(k,v){

    $('<option value="'+k+'">&nbsp;&nbsp;'+v+'</option>').appendTo("select[name=category]");

    $('<div><ul class="su-hiden"></ul></div>').attr('id',k).addClass('folder').appendTo("#user-list");
    $('<div><span class="category-name">'+v+'</span></div>').prepend('<span class="folder-closed"></span>').addClass('folder-head').prependTo('#'+k);
    
    $('<span></span>').addClass('c_delete_button').click(function(){
        if(confirm(chrome.i18n.getMessage('deletecategoryconfirm'))){
          delCategory(k);
        }
    }).appendTo('#'+k+' > .folder-head');
/*
    $('<span></span>').addClass('c_edit_button').click(function(){
      $('#'+k).find('.category-name').hide().append('<input type="text" name="category-rename">');
    }).appendTo('#'+k+' > .folder-head');
*/
  
  });
  $('<div><ul></ul></div>').attr('id',"root").addClass('rootlist').appendTo("#user-list");
  
  $.each(d,function(k,v){
    $('<li><label onclick="user_load('+k+');">'+v.label+'</label><a href="javascript:del('+k+');" class="user-delete" title="'+chrome.i18n.getMessage('deletesiteuser')+'"></a><a href="javascript:user_load('+k+');" class="user-load" title="'+chrome.i18n.getMessage('loadsiteuser')+'"></a></li>').appendTo("#"+v.category+" > ul");
    if(!$("#"+v.category).hasClass('process')){

      $("#"+v.category+' > .folder-head:not(.process)').click(function(){
        $("#"+v.category+' > ul').toggle();
/*        $("#"+v.category).find('.folder-closed').addClass('folder-open-t').removeClass('folder-closed');
        $("#"+v.category).find('.folder-open').addClass('folder-closed').removeClass('folder-open');
        $("#"+v.category).find('.folder-open-t').addClass('folder-open').removeClass('folder-open-t');
*/
      }).addClass('process');
    }
  });
}

function del(i){
  if(!confirm(chrome.i18n.getMessage('deleteuserconfirm'))){
    return false;
  }
  var d = JSON.parse(localStorage.siteuser);
  d.splice(i,1);
  localStorage.siteuser = JSON.stringify(d);
  init();
}

function delCategory(index){
  var c = typeof(localStorage.category)=='undefined'?{}:JSON.parse(localStorage.category);
  var d = typeof(localStorage.siteuser)=='undefined'?[]:JSON.parse(localStorage.siteuser);
  c[index] = undefined;
  localStorage.category = JSON.stringify(c);
  var a = [];
  for(var i=0;i<d.length;i++){
    if(d[i].category!=index){
      a.push(d[i]);
    }
  }
  localStorage.siteuser = JSON.stringify(a);
  init();
}